package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.base.BaseResult;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.model.MemberInfo;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.IdCardValidator;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;

/**
 * Description: 支付密码 第二步 认证的身份证号是否匹配
 * Created by FHW
 * on 2017/11/10
 */

public class RepaymentPwdTwoActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.et_cardid)
    EditText et_cardid;
    @BindView(R.id.bt_next)
    Button bt_next;
    @BindView(R.id.tv_name)
    TextView tv_name;

    private int type = 0;//0-设置 1- 修改

    private String card_no = "";//填写的证件号
    private String idCardNo;//已验证的证件号

    @Override
    protected int getLayoutId() {
        return R.layout.activity_repayment_pwd_two;
    }

    @OnClick({R.id.bt_next})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_next:
                if (verify()) {
                    SelfUtils.buriedClickData(Self.Action.app_click_modify_payment_verify_identity,
                            Self.Action.app_click_modify_payment_verify_identity_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    Intent intent = new Intent();
                    intent.setClass(mContext, SetTradePwdActivity.class);
                    intent.putExtra("type", type);
                    intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                    startActivityForResult(intent, Constant.REQUST_CODE);
                }
                break;
        }
    }

    private boolean verify() {
        if (card_no.equals("")) {
            ToastUtil.showToast("请输入证件号");
            return false;
        }
        IdCardValidator idCardValidator = new IdCardValidator();
        if (!idCardValidator.isValidatedAllIdcard(card_no)) {
            ToastUtil.showToast("身份证格式错误，请检查");
            return false;
        }
        if (!card_no.equals(idCardNo)) {
            ToastUtil.showToast("身份验证不通过");
            return false;
        }
        return true;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        title_bar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCurrentPageId= Self.Page.app_modify_pay_pwd_identity_verify_page;

        type = getIntent().getIntExtra("type", 0);
        switch (type) {
            case 0:
                title_bar.setTitleText("设置支付密码");
                break;
            case 1:
                title_bar.setTitleText("修改支付密码");
                break;
        }

        et_cardid.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                card_no = s.toString();
                if (card_no.equals("")) {
                    bt_next.setEnabled(false);
                } else {
                    bt_next.setEnabled(true);
                }
            }
        });

    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        isRealNameVerify();
    }

    private void isRealNameVerify() {
        showProgressDialog(false);
        Api.getMemberInfo(mApplication.getUser().getID()).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_server_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        BaseResult result = JsonUtil.json2Object(s, BaseResult.class);
                        if (result.getCode() == Constant.SUC_CODE) {
                            Object data = result.getData();
                            if (data instanceof JSONObject) {
                                JSONObject json = (JSONObject) data;
                                MemberInfo info = JsonUtil.json2Object(json.getJSONObject("MemberInfo").toJSONString(),
                                        MemberInfo.class);
                                if (info != null) {
                                    String name = info.getTrueName();
                                    idCardNo = info.getIDCardNo();
                                    if (TextUtils.isEmpty(name) || TextUtils.isEmpty(idCardNo)) {
                                        //未实名认证
                                        Intent intent = new Intent();
                                        intent.setClass(mContext, RealNameAuthenticationActivity.class);
                                        intent.putExtra(RealNameAuthenticationActivity.GO_RESULT_ACTIVITY_B, false);
                                        startActivity(intent);
                                    } else {
//                                        StringBuilder nameSb = new StringBuilder();
//                                        int nameLength = name.length();
//                                        if (nameLength == 2) {
//                                            tv_name.setText(name.substring(0, 1) + " * 身份证号");
//                                        } else {
//                                            for (int i = 0, length = name.length(); i < length; i++) {
//                                                if (i == 0 || i == length - 1) {
//                                                    nameSb.append(name.substring(i, i + 1));
//                                                } else {
//                                                    nameSb.append(" * ");
//                                                }
//                                            }
//                                            tv_name.setText(nameSb.toString() + "身份证号");
//                                        }
                                        tv_name.setText("*" + name.substring(1, name.length()) + "身份证号");
                                    }
                                }
                            }
                        } else {
                            ToastUtil.showToast(result.getMsg());
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUST_CODE) {
            switch (resultCode) {
                case Constant.RESULT_CODE:
                    setResult(Constant.RESULT_CODE);
                    finish();
                    break;
            }
        }
    }

}
